package com.newworld.dmsapp2.service;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.newworld.dmsapp2.activity.MainActivity;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.fragment.adapter.MessageFragementAdapter;
import com.newworld.dmsapp2.fragment.bean.Message;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.StringUtil;
import com.newworld.dmsapp2.util.Tool;
  
public class ServiceMessageUpdate extends Service {  
    private Timer timer;  
    private TimerTask task;  
    private int count;  
    private User user;
    private Context context;
	private List<Message> messageList;
	private Intent getIntent;
  
   /* public ServiceMessageUpdate(Context context){
    	this.context = context;
    }*/
    @Override  
    public IBinder onBind(Intent intent) {  
        return null;  
    }  
  
    @Override  
    public void onCreate() {  
        super.onCreate();  
        context = getApplicationContext();
        initData();
        //getIntent = ((Activity) getApplicationContext()).getIntent();
        //count = getIntent.getExtras().getInt("count");
        final Intent intent = new Intent();  
        intent.setAction(Config.SERVICE_MESSAGE_UPDATENUM);  
  
        timer = new Timer();  
        task = new TimerTask() {  
  
            @Override  
            public void run() {  
                //intent.putExtra("count", ++count);  
            	if (Tool.isNetworkAvailable(context)) {
            		getMessage();
                	intent.putExtra("count", count); 
                    sendBroadcast(intent);  
                    Log.e("ServiceMessageUpdate", "接收广播:"+count);
                    //Toast.makeText(context, "接收广播:"+count, Toast.LENGTH_SHORT).show();
            	}else{
            		 Log.e("ServiceMessageUpdate", "请连接网络"+count);
            		//Toast.makeText(context, "请连接网络", Toast.LENGTH_SHORT).show();
            	}
            	
            }  
        };  
        timer.schedule(task, 1000, 30*1000);  
    }  
   
    
    private void initData(){
    	user = SingleSample.getInstance(context).getUser();
    }
    @Override  
    public void onDestroy() {  
        super.onDestroy();  
        timer.cancel();  
    } 
    
    /**
     * 获取消息序列
     */
    private void getMessage() {
    	String message;
			if (Tool.isNetworkAvailable(context)) {
				try {
					String setsessionid = "";
					user = SingleSample.getInstance(context)
							.getUser();
					if (null != user) {
						if (null != user.getSessionId()
								&& !user.getSessionId().equals("")) {
							setsessionid = user.getSessionId();
						}
					}
					String url = "";
					/*if (null != user
							.getFunctionlistFromUser(Config.FUNCTION_PERSONNAL_MESSAGE)
							&& null != user.getFunctionlistFromUser(
									Config.FUNCTION_PERSONNAL_MESSAGE).get(
									0)) {*/
						url = Config.SERVER_URL
								+ "getMessageController.do?personalMessageNum";
						// 注册请求
						Map<String, String> map = new HashMap<String, String>();
						/*map.put("functionCode",
								Config.FUNCTION_PERSONNAL_MESSAGE);*/
						Log.e("获取未读消息的数量url", url);
						String result = HttpUtil.postRequestSe(url, map,
								setsessionid);
						Log.e("获取未读消息的数量", result);
						JSONObject jsonObj = new JSONObject(result);
						if (jsonObj.getString("flag")
								.equals("success")) {
							String rows = jsonObj.getString("rows");
							String total = jsonObj.getString("total");
							if(null!=total&&!total.equals("")){
								count = Integer.parseInt(total);
							}
							MainActivity.unreadnum = count;
							Log.e("获取未读消息的数量count", count+"");	
							/*if (total.equals("0")) {
								messageList = new ArrayList<Message>();
							} else {
								if (!rows.equals("")) {
									Type type = new TypeToken<List<Message>>() {
									}.getType();
									Gson gson = new Gson();
									messageList = gson.fromJson(rows, type);
									count = 77;
									MainActivity.unreadnum = count;
									for (Message m : messageList) {
										if(!StringUtil.isStringEqual(m.getMessageStatusType(), Config.MESSAGE_STATUS_READED))
										count++;
									}

								} 
							}*/

						}
						message = jsonObj.getString("message");
						Log.e("ServiceMessageUpdate", "广播接收消息"+message);
					/*} else {
						Log.e("ServiceMessageUpdate", "无法获取消息地址");
					}*/

				} catch (Exception e) {
					e.printStackTrace();
					Log.e("ServiceMessageUpdate", "获取消息失败");
				}

			}
    }

}  